/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package redinftel.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import redinftel.entidades.Perfil;
import redinftel.entidades.Usuario;
import redinftel.sesiones.PerfilFacadeRemote;
import redinftel.sesiones.UsuarioFacadeRemote;

/**
 *
 * @author Curro
 */
public class registerServlet extends HttpServlet {
    @EJB
    private PerfilFacadeRemote perfilFacade;

    @EJB
    private UsuarioFacadeRemote usuarioFacade;
    final String USUARIO = "usuario";

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, ParseException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String email = request.getParameter("email");
            System.out.println(email);
            String pass = request.getParameter("password");
            String name = request.getParameter("nombre");
            String surname = request.getParameter("apellidos");

            surname = URLDecoder.decode(surname, "UTF-8");
            pass = URLDecoder.decode(pass, "UTF-8");
            name = URLDecoder.decode(name, "UTF-8");
            email = URLDecoder.decode(email, "UTF-8");

            String birthday = request.getParameter("nacimiento");
            String sex = request.getParameter("sexo");

            if (email.equals("") || pass.equals("") || name.equals("")
                    || surname.equals("") || birthday.equals("")
                    || sex.equals("")) {
                out.println("-1");
            } else if (!validarEmail(email)) {
                out.println("-2");
            } else {
                List<Usuario> usuario = usuarioFacade.findByEmail(email);
                if (!usuario.isEmpty()) {
                    out.println("-3");
                } else {
                    try {
                        //Obtencion fechas
                        SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
                        Date parse = df.parse(birthday);
                        System.out.println(parse);
                        Date fechaActual = new Date();

                        Integer PK = Integer.parseInt(usuarioFacade.findPK().toString()) + 1;
                        String codigo = getCadenaAlfanumAleatoria(6);
                        Usuario nuevoUsuario = new Usuario();
                        nuevoUsuario.setEmail(email);
                        nuevoUsuario.setCodigoValidacion(codigo);
                        nuevoUsuario.setEstado("ACTIVO");
                        nuevoUsuario.setIdUsuario(new BigDecimal(PK));
                        nuevoUsuario.setContrasenya(pass);

                        //Construccion datos perfil nuevo usuario
                        Perfil nuevoPerfil = new Perfil();
                        nuevoPerfil.setIdUsuario(new BigDecimal(PK));
                        nuevoPerfil.setNombre(name);
                        nuevoPerfil.setApellidos(surname);
                        nuevoPerfil.setFechaNacimiento(parse);
                        nuevoPerfil.setFechaRegistro(fechaActual);
                        nuevoPerfil.setSexo(sex);

                        //Insercion datos
                        usuarioFacade.create(nuevoUsuario);
                        perfilFacade.create(nuevoPerfil);

                        nuevoUsuario.setPerfil(nuevoPerfil);
                        HttpSession session = (HttpSession) request.getSession(true);
                        session.setAttribute(USUARIO, nuevoUsuario);
                        out.println(session.getId());

                    } catch (ParseException ex) {
                        out.println("-4");
                    }
                }
            }
        } finally {
            out.close();
        }
    }

    public boolean validarEmail(String email) {
        Pattern p = Pattern.compile("^[\\w\\-\\_]+(\\.[\\w\\-\\_]+)*@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$");
        Matcher m = p.matcher(email);
        if (m.find()) {
            //Es correcta
            return true;
        } else {
            //No es correcta
            return false;
        }
    }

    public String getCadenaAlfanumAleatoria(int longitud) {
        String cadenaAleatoria = "";
        long milis = new java.util.GregorianCalendar().getTimeInMillis();
        Random r = new Random(milis);
        int i = 0;
        while (i < longitud) {
            char c = (char) r.nextInt(255);
            if ((c >= '0' && c <= 9) || (c >= 'A' && c <= 'Z')) {
                cadenaAleatoria += c;
                i++;
            }
        }
        return cadenaAleatoria;
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (ParseException ex) {
            Logger.getLogger(registerServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (ParseException ex) {
            Logger.getLogger(registerServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
